package main

import (
	"fmt"
	"log"
	"sync"

	"github.com/alibaba/sentinel-golang/core/base"

	"github.com/alibaba/sentinel-golang/core/flow"

	sentinel "github.com/alibaba/sentinel-golang/api"
)

const resName = "example-flow-qps-resource"

func main() {
	// 初始化一个sentinel
	err := sentinel.InitDefault()
	if err != nil {
		log.Fatalf("初始化sentinel出错: %v \n", err)
	}

	// 配置限流规则
	_, err = flow.LoadRules([]*flow.Rule{
		{
			Resource:               resName,
			TokenCalculateStrategy: flow.Direct,
			Threshold:              10,
			StatIntervalInMs:       1000,
			ControlBehavior:        flow.Throttling,
		},
	})
	if err != nil {
		log.Fatalf("加载限流规则失败: %+v \n", err)
		return
	}

	wg := sync.WaitGroup{}
	wg.Add(12)
	for i := 0; i < 12; i++ {
		// time.Sleep(time.Millisecond * 120)
		go func() {
			e, block := sentinel.Entry(resName, sentinel.WithTrafficType(base.Inbound))
			if block != nil {
				fmt.Println("block住了, ", block)
			} else {
				fmt.Println("检查通过")
				e.Exit()
			}
			wg.Done()
		}()
	}

	wg.Wait()
}
